<?php
/**
 * Return navigation links to pages (Prev 1, 2 ... 10 Next).
 *
 * <example>
 * <helper()->Pager(10, 5, 4)/>
 * </example>
 *
 * @author Anton Danilchenko <anton.danilchenko@gmail.com>
 */
class Templum_Helper_Pager implements Templum_Helper_Interface {
	/**
	 * Return result of current helper.
	 *
	 * @param string $sData: processing string
	 * @param array $aParams: 0 - all pages, 1 - count of show links in center, 2 - current page
	 */
	public function handle(&$sData, $aParams=array()) {
		// set correct params
		$this->_setCorrect(@$aParams[0]);
		$this->_setCorrect(@$aParams[1]);
		$this->_setCorrect($aParams[2]);
		// set additional parameters
		$iStart = $aParams[2] - (int)($aParams[1]/2);
		$iEnd   = $aParams[2] + (int)($aParams[1]/2);
		// prepare params
		if ($iStart < 1) {
			$iEnd = $iEnd + (1 - $iStart);
			$iStart = 1;
		}
		if ($iEnd > $aParams[0]) {
			$iStart = $iStart - ($iEnd - $aParams[0]);
			$iEnd = $aParams[0];
		}
		if ($iStart < 1)
			$iStart = 1;
		// current page not real
		if ($aParams[2] > $aParams[0])
			$aParams[2] = $aParams[0];
		// print pages
		$sData = $this->_getPagesLinks($aParams[0], $aParams[2], $iStart, $iEnd, '<', '>', ' ', $sData);
	}


	/**
	 * Set number to one if value isn't number or less of one.
	 *
	 * @param int $iNumber: checked number
	 */
	private function _setCorrect(&$iNumber) {
		// automatic set page number (special for Probus framework)
		if (class_exists('Probus'))
			$iNumber = Probus::Url()->get('page', 1);
		// check number
		if (! is_numeric($iNumber) OR $iNumber < 1)
			$iNumber = 1;
	}


	/**
	 * Set number to one if value isn't number or less of one.
	 *
	 * @param int $iNumber: checked number
	 */
	private function _getPagesLinks($iAllPages, $iCurrent, $iFrom, $iTo, $sPrevText='', $sNextText='', $sDelimiter='', $sPrefix='') {
		// result links
		$aLinks = array();
		$iPrev = $iCurrent - 1;
		$iNext = $iCurrent + 1;
		// start navigation block
		$aLinks[] = '<div class="navigarion">';
		// set Prev
		if ('' != $sPrevText AND $iPrev > 1)
			$aLinks[] = "<a class='prev' href='{$sPrefix}{$iPrev}'>{$sPrevText}</a>";
		// set First
		if ($iFrom > 1)
			$aLinks[] = "<a class='first' href='{$sPrefix}1'>1</a>";
		// set center links
		for ($iPageNum=$iFrom; $iPageNum<=$iTo; $iPageNum++) {
			$sClassName = ($iPageNum==$iCurrent) ? 'link selected' : 'link';
			$aLinks[] = "<a class='{$sClassName}' href='{$sPrefix}{$iPageNum}'>{$iPageNum}</a>";
		}
		// set End
		if ($iTo < $iAllPages)
			$aLinks[] = "<a class='last' href='{$sPrefix}{$iAllPages}'>{$iAllPages}</a>";
		// set Next
		if ('' != $sNextText AND $iNext < $iAllPages)
			$aLinks[] = "<a class='next' href='{$sPrefix}{$iNext}'>{$sNextText}</a>";
		// end navigation block
		$aLinks[] = '</div>';
		// return links
		return implode($sDelimiter, $aLinks);
	}
}